package com.zzz.message.service;

import com.alibaba.fastjson2.JSON;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @BelongsProject: oj-project
 * @BelongsPackage: com.zzz.message.config
 * @Author: zhai
 * @CreateTime: 2025-10-25  20:01
 * @Description: TODO 阿里云短信服务
 * @Version: 1.0
 */
@Component
@Slf4j
public class AliSmsService {
    @Resource
    private Client aliClient;  // 修正变量命名一致性

    //业务配置
    @Value("${sms.aliyun.templateCode:}")
    private String templateCode;

    @Value("${sms.send-message:true}")
    private boolean sendMessage;

    @Value("${sms.sign-name:}")  // 修正属性名: singName -> signName
    private String signName;

    public String generateCode(Integer codeQuantity) {
        // 定义验证码字符集：数字0-9，大小写字母a-z，A-Z
        String charSet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        StringBuilder code = new StringBuilder();

        // 使用传入的codeQuantity作为验证码长度
        int codeLength = codeQuantity;

        for (int i = 0; i < codeLength; i++) {
            // 生成随机索引，范围0到charSet.length()-1
            int index = (int) (Math.random() * charSet.length());
            // 根据索引获取字符并添加到验证码中
            code.append(charSet.charAt(index));
        }

        return code.toString();
    }

    /**
     * 发送短信验证码
     *
     * @param phone 手机号码
     * @param code 验证码
     */
    public boolean sendMobileCode(String phone, String code) {
        Map<String, String> params = new HashMap<>();
        params.put("code", code);
        return sendTempMessage(phone, templateCode, params);
    }

    /**
     * 发送模板消息
     *
     * @param phone 手机号码
     * @param templateCode 模板编码
     * @param params 参数映射
     */
    public boolean sendTempMessage(String phone, String templateCode,
                                   Map<String, String> params) {
        if (!sendMessage) {
            log.error("短信发送通道关闭，发送失败......" + phone);
            return false;
        }

        SendSmsRequest sendSmsRequest = new SendSmsRequest();
        sendSmsRequest.setPhoneNumbers(phone);
        sendSmsRequest.setSignName(signName);  // 使用修正后的变量名
        sendSmsRequest.setTemplateCode(templateCode);
        sendSmsRequest.setTemplateParam(JSON.toJSONString(params));

        try {
            SendSmsResponse sendSmsResponse = aliClient.sendSms(sendSmsRequest);  // 修正变量名调用
            SendSmsResponseBody responseBody = sendSmsResponse.getBody();

            if (!"OK".equalsIgnoreCase(responseBody.getCode())) {
                // 修正日志语句中的语法错误
                log.error("短信{} 发送失败，失败原因:{}.... ", JSON.toJSONString(sendSmsRequest), responseBody.getMessage());
                return false;
            }
            return true;
        } catch (Exception e) {
            // 修正日志语句中的语法错误
            log.error("短信{} 发送失败，失败原因:{}.... ", JSON.toJSONString(sendSmsRequest), e.getMessage());
            return false;
        }
    }
}
